package com.googlecode.jmicroerp.wicket.components.grid;

import java.lang.reflect.InvocationTargetException;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractToolbar;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.export.IDataExporter;
import org.apache.wicket.extensions.markup.html.repeater.data.table.export.IExportableColumn;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A toolbar that provides links to download the data represented by all
 * {@link IExportableColumn}s in the table exported to formats supported by the
 * {@link IDataExporter}s configured.
 *
 * @author Jesse Long, Alexandru.Codescu
 * @see IDataExporter
 * @see IExportableColumn
 */
public class ActionToolbar extends AbstractToolbar {

    private static final long serialVersionUID = 1L;
    private static final IModel<String> DEFAULT_FILE_NAME_MODEL = new ResourceModel("datatable.export-file-name");
    private static final Logger LOGGER = LoggerFactory.getLogger(ActionToolbar.class);
    private ActionButton adaugareButton;
    private ModalWindow window;
    private Component target;

    /**
     * Creates a new instance with the default message model. This instance will
     * use "export." as the exported file name prefix.
     *
     * @param table The data table this toolbar belongs to.
     */
    public ActionToolbar(final DataTable<?, ?> table, Component target, ActionButton adaugareButton) {
        this(table, adaugareButton);
        this.target = target;
    }

    
    /**
     * Creates a new instance with the provided data table and file name model.
     *
     * @param table The table to which this toolbar belongs.
     * @param fileNameModel The model of the file name. This should exclude the
     * file extensions.
     */
    public ActionToolbar(DataTable<?, ?> table, ActionButton adaugareButton) {
        super(table);
        this.adaugareButton = adaugareButton;
    }
    
    private ModalWindow createModalWindow() {
        final ModalWindow modal1 = new ModalWindow("modal1") {

            @Override
            public void show(AjaxRequestTarget target) {
                super.show(target);
                this.getContent().modelChanged();
            }
            
        };
        
        PageParameters pageParameters = adaugareButton.getPageParameters();

        try {
            if ((pageParameters.getPanelEdit(modal1.getContentId()) != null)) {
                PopUpPanel panel = pageParameters.getPanelEdit(modal1.getContentId());
                panel.setWindow(modal1);
                modal1.setContent(panel);
            }
        } catch (IllegalAccessException iaex) {
        	LOGGER.error(iaex.getMessage(), iaex);
        } catch (IllegalArgumentException iaex) {
        	LOGGER.error(iaex.getMessage(), iaex);
        } catch (InstantiationException iex) {
        	LOGGER.error(iex.getMessage(), iex);
        } catch (InvocationTargetException itex) {
        	LOGGER.error(itex.getMessage(), itex);
        } catch (NoSuchMethodException nsmex) {
        	LOGGER.error(nsmex.getMessage(), nsmex);
        }
        
        modal1.setCookieName("modal-3");

        modal1.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() {
            @Override
            public boolean onCloseButtonClicked(AjaxRequestTarget target) {
                return true;
            }
        });

        modal1.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
            @Override
            public void onClose(AjaxRequestTarget art) {
                art.add(target);
            }
        });
        return modal1;
    }

    /**
     * {@inheritDoc }
     */
    @Override
    protected void onInitialize() {
        super.onInitialize();

        WebMarkupContainer td = new WebMarkupContainer("td");
        add(td);

        td.add(AttributeModifier.replace("colspan", new AbstractReadOnlyModel<String>() {
            private static final long serialVersionUID = 1L;

            @Override
            public String getObject() {
                return String.valueOf(getTable().getColumns().size());
            }
        }));

        td.add(createEditLink("editLink"));
        window = createModalWindow();
        td.add(window);
    }

    protected Component createEditLink(String componentId) {
        final PageParameters pageParameters = adaugareButton.getPageParameters();
        AjaxLink<Void> link = new AjaxLink<Void>(componentId) {
            @Override
            public void onClick(AjaxRequestTarget target) {
                try {
                    if (adaugareButton != null) {
                        if (pageParameters.getPageInsert() == null) {
                            window.show(target);
                        } else {
                            setResponsePage(pageParameters.getPageInsert());
                        }
                    }
                } catch (IllegalAccessException iaex) {
                    LOGGER.error(iaex.getMessage(), iaex);
                } catch (IllegalArgumentException iaex) {
                    LOGGER.error(iaex.getMessage(), iaex);
                } catch (InstantiationException iex) {
                    LOGGER.error(iex.getMessage(), iex);
                } catch (InvocationTargetException itex) {
                    LOGGER.error(itex.getMessage(), itex);
                } catch (NoSuchMethodException nsmex) {
                    LOGGER.error(nsmex.getMessage(), nsmex);
                }
            }
        };
        link.setVisible(adaugareButton.canDisplay());
        link.add(new Label("linkName", adaugareButton.getInsertLabel()));
        
        return link;
    }
}
